package main

import (
	"flag"
	"fmt"
	"strings"
	"strconv"
	"net/url"
	"math/rand"
	"time"
	"os"
)

type resource struct {
	url string
	target string
	start int
	end int

}


func ruleResource() []resource{
	var res []resource
	r1:=resource{
		url:"http://localhost:8888/",
		target:"",
		start:0,
		end:0,

	}
	r2:=resource{
		url:"http://localhost:8888/list/{$id}.html",
		target:"{$id}",
		start:1,
		end:21,
	}

	r3:=resource{
		url:"http://localhost:8888/movie/{$id}.html",
		target:"{$id}",
		start:1,
		end:12924,
	}


	res= append(append(append(res, r1), r2), r3)

	return res
}

func buildeUrl(res []resource)[]string{
	var list[]string

	for _,resItem :=range res{
		if len(resItem.target)==0{
			list=append(list,resItem.url)
		}else{
			for i:=resItem.start;i<resItem.end;i++{
				urlStr:=strings.Replace(resItem.url,resItem.target,strconv.Itoa(i),-1)
				list=append(list,urlStr)
			}
		}

	}
	return list
}

func makeLog(current,refer,ua string)string{
	u:=url.Values{}
	u.Set("time","1")
	u.Set("url",current)
	u.Set("refer",refer)
	u.Set("ua",ua)

	paramsStr:=u.Encode()
	logTemplate:="127.0.0.1 - - [19/Aug/2018:16:39:14 +0800] \"OPTIONS /dig?{$paramsStr} HTTP/1.1\" 200 43 \"-\" \"{$ua}\" \"-\""
	log:=strings.Replace(logTemplate,"{$paramsStr}",paramsStr,-1)
	log=strings.Replace(logTemplate,"{$ua}",ua,-1)
	return log}





func randInt(min,max int) int{
	r:=rand.New(rand.NewSource(time.Now().UnixNano()))
	if min>max{
		return max
	}
	return r.Intn(max-min)+min
}


func main() {
	total:=flag.Int("total",10000,"how manay create nium")
	filepath:=flag.String("filepath","/usr/local/var/log/nginx/access.log","filepath")
	flag.Parse()

	res:=ruleResource()
	list:=buildeUrl(res)

	fmt.Println(list)



	fmt.Println(total,filepath)
	var logStr string
	for i:=0;i<*total;i++{

		currentUrl:=list[randInt(0,len(list)-1)]
		refUrl:=list[randInt(0,len(list)-1)]
		ua:=list[randInt(0,len(list)-1)]

		logStr=logStr+makeLog(currentUrl,refUrl,ua)+"\n"
		//ioutil.WriteFile(*filepath,[]byte(logStr),0644)
	}
	fd,_:=os.OpenFile(*filepath,os.O_RDWR|os.O_APPEND,06444)
	fd.Write([]byte(logStr))
	fd.Close()

	fmt.Println("done.\n")

}
